#include <msp430.h>
#include "main.h"

unsigned int event_counter = 0;

void ButtonSelect()
{
	pwm_out[1]++;
	pwm_out[1] &= RESOLUTION;
}
void ButtonEnter()
{
	pwm_out[1]--;
	pwm_out[1] &= RESOLUTION;
}
void init()
{
	unsigned int index;
	P1DIR = HEATER_PWM | AUX_OUT;
	P1OUT = 0x00;
	P2DIR = LEDS_OUT;	
	P2OUT = 0x00;

	P1DIR = 0X01;
	P2DIR = 0XFF;
	P2OUT = 0X00;

	for(index = 0; index < PWM_OUTS; index++)
		pwm_out[index] = 0x00;

	//Configure ADC to be ready to be enabled on notice.
	ADC10CTL0 = ADC10ON | REF2_5V | SREF_1 | ADC10SHT_2 | ADC10IE; //2.5V reference generator, Vref - Vss sampling, 64 clock cycle sampling time.
	ADC10AE0 = HEATER_FB | SENSOR_SIG;

	buzzkeeper.ButtonSelect = ButtonSelect;
	buzzkeeper.ButtonEnter = ButtonEnter;
}

void adjustHeater()
{
	if(event_counter++ == 640)
	{
		setHeaterPwm();
		event_counter = 0; //Reset the counter
	}
}

int main()
{
	//Halt the watchdog.
	WDTCTL = WDTPW + WDTHOLD;

	//Setup 16 Mhz run speed, fDCO(15, 3) / RSEL 15
	//More info in msp430g2452 data sheet p. 25
	DCOCTL = DCO0 | DCO1;
	BCSCTL1 = RSEL3 | RSEL2 | RSEL1 | RSEL0;

	init();

//	event_handler = adjustHeater;

	//Configure Timer A for more info: MSP430x2xx Family User's Guide p. 357-376
	TACTL = TASSEL_1 | MC_1; //TimerA run in UP mode with ACLK as the source.
	TACCTL0 = CCIE; 
	CCR0 = EVENT_TIMER;
	TACCTL1 = CCIE;
	CCR1 = 1;

	while(1)
	{	
		__bis_SR_register(LPM3_bits + GIE); //LPM3 w/ interrupts.
		//Increase the CCR1 register to execute on the next cycle
		CCR1+=2;
		if(CCR1 > CCR0) CCR1 = 0x01;
	}
	return 0;
}

/*CCR0 Interrupt*/
#ifdef __GNUC__
__attribute__((interrupt(TIMER0_A0_VECTOR)))
#else
#pragma vector = TIMER0_A0_VECTOR
	__interrupt
#endif
void TIMER0_A0_ISR(void)
{
	unsigned char state;
	state = (P1IN ^ 0xFF) & (BUTTON_SEL | BUTTON_ENT); //Active Low

	//64Hz event timer
	switch(state)
	{
		case BUTTON_SEL | BUTTON_ENT:
			buzzkeeper.inputs.both_accum++;
			break;
		case BUTTON_SEL:
			buzzkeeper.inputs.select_accum++;
			break;
		case BUTTON_ENT:
			buzzkeeper.inputs.enter_accum++;
			break;
		default:
			if(buzzkeeper.inputs.both_accum > 16)
			{
			}
			else if(buzzkeeper.inputs.select_accum > 16)
			{
				ButtonSelect();
			}
			else if(buzzkeeper.inputs.enter_accum > 16)
			{
				ButtonEnter();
			}
			buzzkeeper.inputs.both_accum = 0;
			buzzkeeper.inputs.select_accum = 0;
			buzzkeeper.inputs.enter_accum = 0;
			break;
	}
}
